import axios from "axios"
import messageInfo from "@/utils/message"
import cookies from "@/utils/auth"
import defaultSettings from './config'
import store from "@/store"


const api=axios.create({
    baseURL:"/api",
    // baseURL:"http://39.104.21.39:8899",
    // baseURL:"http://ceshi13.dishait.cn",
    timeout:5000,
    // headers:{},
    // withCredentials:true,
    // validateStatus:function(status){
    // },
    // transformRequest:[function(data,headers){
    //     return data
    // }],
    // transformResponse:[function(data){
    //     return data
    // }],
    // responseType:"json",
    // xsrfCookieName:"XSRF-TOKEN",
    // xsrfHeaderName:"X-XSRF-TOKEN",

})

api.interceptors.request.use(
  function(config){
    const token=cookies.getToken()
    //如果有token，增加headers请求头
    if(token && token!==""){
      config.headers['token']=token
      config.headers['domain']=defaultSettings.domain
    }
    
    //请求之前配置
    return config
  },(error)=>{
    //请求错误配置
    console.log("req: ",error)
    messageInfo.notific.error(error)
    return Promise.reject(error)
  }
)

api.interceptors.response.use(
  (response)=>{
    //响应数据
    console.log("resp-success: ",response)
    if(!response.data.responseData && !response.data.responseMsg){
      return response.data
    }else{
      if(response.data.success){
        return response.data.responseData
      }else{
        console.log("error",response)
        let errorData={
          responseMsg: response.data.responseMsg
            ? response.data.responseMsg
            : "信息获取失败，请联系管理员"
        }
        if(response.data.responseMsg=="非法token"){
          errorData.responseMsg="非法token，请先登录"
          store.dispatch("forceLogout").finally(()=>{
            // window.location.href="/login"
            location.reload()
          })
        }
        messageInfo.notific.error(errorData.responseMsg)
        
        return errorData
      }
    }
    
    
  },(error)=>{
    //响应错误配置
    console.log("resp: ",error)
    if(error.status===404 || error.status===401){
      messageInfo.notific.error("请求尚未授权，请联系后台管理员")
    }else{
      messageInfo.notific.error("服务器连接失败，请检查网络")
    }
    
    return Promise.reject(error)
  }
)
  

export default api